package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.ws.RespectBinding;
import java.io.IOException;

/**
 * 监听器  接收 传过来的消息 发送到 es 上 数据同步
 */
@Component
public class ItemListener {

    @Autowired
    RestHighLevelClient client;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.update.queue"),
            exchange = @Exchange(name = "item.direct"),
            key = "item.update"
    ))
    public void handleUpdateMessage(String msg) throws IOException {
        ItemDoc itemDoc = JSON.parseObject(msg, ItemDoc.class);
        IndexRequest request = new IndexRequest("hamll");
        request.id(itemDoc.getId().toString());
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.delete.queue"),
            exchange = @Exchange(name = "item.direct"),
            key = "item.delete"
    ))
    public void handleDeleteMessage(String id) throws IOException {
        DeleteRequest request = new DeleteRequest("hamll", id);
        client.delete(request, RequestOptions.DEFAULT);
    }
}
